package com.play.base_activity;

import java.util.Iterator;
import java.util.Stack;

/**
 * 所有 Activity 的 管理类
 * 使用 Stack 做核心容器
 * <p>
 * Author by jmf,
 * Date on 2021/12/8.
 */
public class ActivitiesManager {

    /**
     * 所有  activity  的容器
     * pop  peek push empty
     */
    private static Stack<BaseActivity> activityStack;

    /**
     * 返回栈顶 第 1 个 处于活动中的Activity
     *
     * @return
     */
    public static BaseActivity getTopActivityInstance() {
        if (null != activityStack) {
            BaseActivity baseAbastractActivity;
            for (int i = activityStack.size() - 1; i >= 0; --i) {
                baseAbastractActivity = activityStack.get(i);
                if (!baseAbastractActivity.isFinishing()) {
                    // 从栈顶往下数  返回第一个还在活动的 activity
                    return baseAbastractActivity;
                }
            }
        }
        return null;
    }

    /**
     * 返回栈顶 第 2 个 处于活动中的Activity
     *
     * @return
     */
    public static BaseActivity getSecondActivityInstance() {
        if (null != activityStack) {
            BaseActivity baseActivity;
            int index = 0;
            for (int i = activityStack.size() - 1; i >= 0; --i) {
                baseActivity = activityStack.get(i);
                if (!baseActivity.isFinishing()) {
                    // 从栈顶往下数  返回第一个还在活动的 activity
                    if (index == 2) {
                        return baseActivity;
                    }
                    index++;
                }
            }
        }
        return null;
    }

    /**
     * 基于 BaseActivity 新建的 Activity 入管理栈
     *
     * @param baseActivity
     */
    public static void addActivity(BaseActivity baseActivity) {
        if (null == activityStack) {
            activityStack = new Stack<BaseActivity>();
        }
        if (!activityStack.contains(baseActivity)) {
            activityStack.push(baseActivity);
        }
    }

    /**
     * 移出管理栈
     */
    public static void removeActivty(BaseAbastractActivity baseAbastractActivity)  {
        if (null != activityStack) {
            if (activityStack.contains(baseAbastractActivity)) {
                activityStack.remove(baseAbastractActivity);
            }
        }
    }


    /**
     * 退出登录时  回收所有 Activity
     */
    public static void finishAllActivity() {
        if (null != activityStack) {
            Iterator<BaseActivity> activityIterator = activityStack.iterator();
            while (activityIterator.hasNext()){
                BaseAbastractActivity activity = activityIterator.next();
                if(!activity.isFinishing()){
                    activity.finish();
                }
                activityIterator.remove();
            }
            activityStack.clear();
        }
    }

}
